import React, { useState, useEffect } from 'react';

function CanvasCaptcha(props) {
    const [text, setText] = useState(''); // 验证码文本
    const [code, setCode] = useState(''); // 验证码编码
    const [canvas, setCanvas] = useState(null); // canvas 对象
    const [ctx, setCtx] = useState(null); // canvas 上下文
    const [input, setInput] = useState(''); // 输入的验证码
    useEffect(() => {
        if (canvas) {
            drawCaptcha();
            refreshCaptcha()
        }
    }, [canvas]);
    // 生成随机数
    const randomNum = (min, max) => {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    };
    // 生成随机字符
    const randomChar = () => {
        let chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        return chars[randomNum(0, chars.length - 1)];
    };
    // 生成验证码
    const drawCaptcha = () => {
        let width = 70;
        let height = 50;
        let fontSize = 20;
        let fontColor = ['#000'];
        let bgColor = ['#fff'];
        let fontStyle = ['normal'];
        let len = 4; // 验证码长度
        let code = '';
        let canvas = document.getElementById('canvas');
        canvas.width = width;
        canvas.height = height;
        let ctx = canvas.getContext('2d');
        ctx.textBaseline = 'middle';
        ctx.fillStyle = bgColor[randomNum(0, bgColor.length - 1)];
        ctx.fillRect(0, 0, width, height);
        for (let i = 0; i < len; i++) {
            let char = randomChar();
            code += char;
            ctx.font = fontStyle[randomNum(0, fontStyle.length - 1)] + ' ' + fontSize + 'px sans-serif';
            ctx.fillStyle = fontColor[randomNum(0, fontColor.length - 1)];
            let x = (width - 10) / len * i + 10;
            let y = height / 2;
            let deg = randomNum(-30, 30);
            ctx.translate(x, y);
            ctx.rotate(deg * Math.PI / 180);
            ctx.fillText(char, 0, 0);
            ctx.rotate(-deg * Math.PI / 180);
            ctx.translate(-x, -y);
        }
        setText(code);
        // setCode(btoa(code));
        // onCaptcha({ text: code, code: btoa(code) });
        // 刷新验证码


    };

    const refreshCaptcha = () => {
        drawCaptcha();


        //传给login页面验证码

        // getData()
    };
    useEffect(() => {
        console.log(text);
        props.changeNames(text)
    }, [text])
    //   const getData=()=>{
    //     console.log(text);
    //     props.changeNames(text)
    //   }


    return (
        <div>
            <canvas id="canvas" ref={(el) => setCanvas(el)} onClick={refreshCaptcha} />
        </div>
    );
}
export default CanvasCaptcha;